import re
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings
from rest_framework import serializers

from celery_tasks.email.tasks import send_email
from user.models import User
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from django.core.mail import send_mail
from itsdangerous import TimedJSONWebSignatureSerializer as TJS




class UserSerializer(serializers.ModelSerializer):

    # 显示指明验证字段,因为在模型类中没有的字段
    password2 = serializers.CharField(max_length=20,min_length=8,write_only=True)
    sms_code = serializers.CharField(max_length=6,min_length=6,write_only=True)
    allow = serializers.CharField(write_only=True)

    # 只需要序列化返回
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('id','username','mobile','password','password2','sms_code','allow','token')
        extra_kwargs = {
            'username':{
                'max_length':20,
                'min_length':5,
                'error_messages':{
                    'max_length':'名字过长',
                    'min_length':'名字过短',
                }
            },
            'password': {
                'write_only':True,
                'max_length': 20,
                'min_length': 8,
                'error_messages': {
                    'max_length': '密码过长',
                    'min_length': '密码过短',
                }
            }
        }

    # 验证手机格式
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$',value):
            return serializers.ValidationError('手机格式不正确')

        return value

    # 判断是否选中协议
    def validated_allow(self,value):
        if value !=True:
            return serializers.ValidationError('未选中')
        return value

    # 密码判断
    def validate(self, attrs):

        if attrs['password'] != attrs['password2']:
            return serializers.ValidationError('密码不一致')

        # 密码一一致的话，就进行短信验证
        # 判断短信
            # 1 先获取缓存中短信
        conn = get_redis_connection('verify')
        real_sms_code = conn.get('sms_code_%s' % attrs['mobile'])

        if not real_sms_code:
            return serializers.ValidationError('短信验证码失效')

        if attrs['sms_code'] != real_sms_code.decode():
            return serializers.ValidationError('短信验证码错误')

        return attrs

    def create(self,validated_data):
        print(validated_data)
        # 删除不需要保存的字段数据
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        print(validated_data)

        # 返回一个对象　，这里调用了create_user()或者create()返回一个对象
        user = super().create(validated_data)

        user.set_password(validated_data['password'])
        user.save()


        # 生成token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # user这个数据放进到payload
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 让用户对象生成一个token的属性
        user.token = token

        # 序列化结果返回给前端
        return user


class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class UserEmailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id','email')
        extra_kwargs = {
            'email':{
                'required':True
            }
        }

    # context['request'] 接受视图传递过来数据内容

    def update(self, instance, validated_data):

        # user = self.context['request'].user
        # # mobile= self.context['mobile']
        #
        # user.email = validated_data['email']
        # user.save()
        instance.email=validated_data['email']
        instance.save()

        #
        # tjs = TJS(settings.SECRET_KEY, 300)
        # token = tjs.dumps({'id': instance.id, 'username': instance.username}).decode()


        # 发送邮件
        # send_mail('美多商城邮箱验证', '', settings.EMAIL_FROM, ['13250076716@163.com'],html_message='<a href="www.itcast.cn">传智播客</a>')

        tjs = TJS(settings.SECRET_KEY,300)
        token = tjs.dumps({
            'id':instance.id,
            'username':instance.username
                           }).decode()

        # verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token
        # to_email = '13250076716@163.com'
        # subject = "美多商城邮箱验证"
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url)
        # send_mail(subject, "", settings.EMAIL_FROM, [to_email], html_message=html_message)


        send_email.delay(token,validated_data['email'])


        return instance


class VerifyEmailSerializer(serializers.Serializer):

    token = serializers.CharField(write_only=True)

    def validate(self, attrs):
        # token 解密
        tjs = TJS(settings.SECRET_KEY,300)

        try:
            data = tjs.loads(attrs['token'])
        except:
            raise serializers.ValidationError('错误的token')

        if not data:
            raise serializers.ValidationError('无效的token')

        attrs['data']=data

        return attrs











